package web.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.User;
import domain.response.NoLoginResponse;
import utils.LyyGlobal;
import utils.LyyLogUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;

@WebFilter("/*")
public class FilterImpl implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        String requestURI = request.getRequestURI();//获取请求路径
        LyyLogUtil.logD("请求路径为："+requestURI);
        ArrayList<String> list = new ArrayList<>();
        list.add("/bootstrap-3.4.1-dist");
        list.add("/css");
        list.add("css");
        list.add("/js");
        list.add("/img");
        list.add("/login");
        list.add("/register");
        list.add("/isExsist");
        list.add("/getAllFunction");
        list.add("about/about.html");
        list.add("index");
        list.add("/test");
        list.add("/chat");
        boolean flag = false;
        for (String s : list) {
            if (requestURI.contains(s)) {
                flag = true;
            }
        }
        if (flag) {
            chain.doFilter(req, resp);
        } else {//用户请求了其他的资源，没有登录的话，肯定是要拦截的，已经登录的话就放行
            User user = (User) request.getSession().getAttribute(LyyGlobal.USER_KEY);
            LyyLogUtil.logD("保存到session的用户为："+user);
            if (user != null) {
                chain.doFilter(req, resp);
            } else {
                NoLoginResponse noLoginResponse=new NoLoginResponse();
                noLoginResponse.setErrMsg("网络请求失败：您尚未登录或者登录已经失效，请重新登录后再试！");
                noLoginResponse.setStatus(0);
                noLoginResponse.setErrCode("nologin");
                ObjectMapper objectMapper=new ObjectMapper();
                resp.setContentType("application/json;charset=utf-8");
                objectMapper.writeValue(resp.getOutputStream(),noLoginResponse);
            }
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
